package com.douyinkan.controller;

import com.douyinkan.service.DirectoryScanService;
import com.douyinkan.service.ContentService;
import com.douyinkan.dto.ContentDTO;
import com.douyinkan.service.impl.DirectoryScanServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/directory")
public class DirectoryController {
    
    private static final Logger logger = LoggerFactory.getLogger(DirectoryController.class);
    
    @Autowired
    private DirectoryScanService directoryScanService;
    
    @Autowired
    private ContentService contentService;
    
    // 将DirectoryScanService转换为具体实现类以便访问设置媒体目录的方法
    @Autowired
    private DirectoryScanServiceImpl directoryScanServiceImpl;
    
    @PostMapping("/scan")
    public ResponseEntity<?> scanDirectory(@RequestBody DirectoryScanRequest request) {
        logger.info("=== Directory Scan API Called ===");
        logger.info("Received scan directory request for: {}", request.getDirectory());
        
        try {
            logger.info("Starting directory scan process for: {}", request.getDirectory());
            
            // 扫描目录获取新内容
            logger.info("Calling directoryScanService.scanDirectory()");
            List<com.douyinkan.entity.Content> newContents = directoryScanService.scanDirectory(request.getDirectory());
            logger.info("Directory scan completed, found {} new files", newContents.size());
            
            // 保存新内容到数据库
            logger.info("Saving {} new contents to database", newContents.size());
            int savedCount = 0;
            for (com.douyinkan.entity.Content content : newContents) {
                try {
                    // 将实体转换为DTO并保存
                    ContentDTO contentDTO = convertToDTO(content);
                    contentService.saveContent(contentDTO); // 假设ContentService有保存方法
                    savedCount++;
                    
                    if (savedCount % 10 == 0) { // 每保存10个文件记录一次
                        logger.debug("Saved {} contents so far...", savedCount);
                    }
                } catch (Exception e) {
                    logger.error("Error saving content: {}", content.getFilename(), e);
                }
            }
            
            logger.info("Successfully saved {} contents to database", savedCount);
            logger.info("Directory scan process completed successfully");
            
            ScanResult result = new ScanResult(newContents.size());
            logger.info("Returning scan result with {} new files", result.getNewFilesCount());
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("Critical error during directory scan for: {}", request.getDirectory(), e);
            return ResponseEntity.internalServerError().body("Error scanning directory: " + e.getMessage());
        } finally {
            logger.info("=== Directory Scan API Completed ===");
        }
    }
    
    @PostMapping("/set-media-dir")
    public ResponseEntity<?> setMediaDirectory(@RequestBody DirectoryScanRequest request) {
        logger.info("=== Set Media Directory API Called ===");
        logger.info("Setting media directory to: {}", request.getDirectory());
        
        try {
            logger.info("Calling directoryScanServiceImpl.setCurrentMediaDirectory()");
            // 使用具体实现类来设置媒体目录
            directoryScanServiceImpl.setCurrentMediaDirectory(request.getDirectory());
            
            logger.info("Getting media meta directory");
            String metaDir = directoryScanService.getMediaMetaDir(request.getDirectory());
            logger.info("Set media directory: {}, meta directory: {}", request.getDirectory(), metaDir);
            
            // 返回媒体目录信息
            MediaDirectoryInfo info = new MediaDirectoryInfo(request.getDirectory(), metaDir);
            logger.info("Media directory set successfully");
            return ResponseEntity.ok(info);
        } catch (Exception e) {
            logger.error("Critical error setting media directory: {}", request.getDirectory(), e);
            return ResponseEntity.internalServerError().body("Error setting media directory: " + e.getMessage());
        } finally {
            logger.info("=== Set Media Directory API Completed ===");
        }
    }
    
    @GetMapping("/current")
    public ResponseEntity<?> getCurrentDirectory() {
        logger.info("=== Get Current Directory API Called ===");
        // TODO: 从系统配置中获取当前媒体目录
        // 这里临时返回一个默认值，实际实现需要从配置中获取
        String defaultMediaDir = System.getProperty("user.home") + "/workspace/code/douyinkan/内容";
        String defaultMetaDir = defaultMediaDir + "/myMediaMeta";
        logger.info("Returning current directory: {}", defaultMediaDir);
        logger.info("=== Get Current Directory API Completed ===");
        return ResponseEntity.ok(new MediaDirectoryInfo(defaultMediaDir, defaultMetaDir));
    }
    
    // 辅助方法：将实体转换为DTO
    private ContentDTO convertToDTO(com.douyinkan.entity.Content content) {
        ContentDTO dto = new ContentDTO();
        dto.setFilename(content.getFilename());
        dto.setFilePath(content.getFilePath());
        dto.setContentType(content.getContentType());
        dto.setTitle(content.getTitle());
        dto.setDescription(content.getDescription());
        dto.setDurationSeconds(content.getDurationSeconds());
        dto.setWidth(content.getWidth());
        dto.setHeight(content.getHeight());
        dto.setFileSizeBytes(content.getFileSizeBytes());
        dto.setCreatedAt(content.getCreatedAt());
        dto.setUpdatedAt(content.getUpdatedAt());
        dto.setThumbnailPath(content.getThumbnailPath());
        return dto;
    }
    
    public static class DirectoryScanRequest {
        private String directory;
        
        public String getDirectory() {
            return directory;
        }
        
        public void setDirectory(String directory) {
            this.directory = directory;
        }
    }
    
    public static class ScanResult {
        private int newFilesCount;
        
        public ScanResult(int newFilesCount) {
            this.newFilesCount = newFilesCount;
        }
        
        public int getNewFilesCount() {
            return newFilesCount;
        }
        
        public void setNewFilesCount(int newFilesCount) {
            this.newFilesCount = newFilesCount;
        }
    }
    
    public static class MediaDirectoryInfo {
        private String mediaDirectory;
        private String metaDirectory;
        
        public MediaDirectoryInfo(String mediaDirectory, String metaDirectory) {
            this.mediaDirectory = mediaDirectory;
            this.metaDirectory = metaDirectory;
        }
        
        public String getMediaDirectory() {
            return mediaDirectory;
        }
        
        public void setMediaDirectory(String mediaDirectory) {
            this.mediaDirectory = mediaDirectory;
        }
        
        public String getMetaDirectory() {
            return metaDirectory;
        }
        
        public void setMetaDirectory(String metaDirectory) {
            this.metaDirectory = metaDirectory;
        }
    }
}